<?php
require_once("modules/debug.class.php");
require_once("modules/model/model.class.php");

class XmlDataLoader{
	private static $_instance;
	private $model;

	/**
	 * Default constructor.
	 * @param Model $model model manager instance.
	 * @return XmlDataLoader object.
	 */
	public function __construct($model=null){
		$this->model=$model;
	}

	/**
	 * Reload data from scratch into existing tables.
	 */
	public function load(){
		__debug(__FILE__,__LINE__,"XmlDataLoader::load() - start");
		$root=dirname($_SERVER['SCRIPT_FILENAME'])."/app/dbinit/";
		__debug(__FILE__,__LINE__,"XmlDataLoader::load() - parse entities from [$root].");
		foreach($this->model->getXml()->xpath("entity") as $entity){
			$this->import($entity,$root.$entity->attributes()->name.".xml");
		}
		__debug(__FILE__,__LINE__,"XmlDataLoader::load() - end");
	}

	/**
	 * Import $xmlfile data for entity.
	 * @param XMLElement $entity entity to be loaded.
	 * @param string $xmlfile XML file name.
	 * @return boolean status true=< all is ok, false => error.
	 */
	public function import($entity,$xmlfile){
		$status = true;
		$sql="";
		if(file_exists($xmlfile)){
			__info(__FILE__,__LINE__,"XmlDataLoader::import() - entity=[".$entity->attributes()->name."], file=[$xmlfile]");
			$xml = simplexml_load_file($xmlfile, 'SimpleXMLElement',LIBXML_NOCDATA);
			//__debug(__FILE__,__LINE__,"Model::reload() - data=[".print_r($xml,true)."]");
			foreach($xml->insert as $insert){
				$sql.= $this->generateSQL($insert);
				__debug(__FILE__,__LINE__,"XmlDataLoader::import() - insert data=[".$sql."]");
				try{
				//$this->connection->executeScriptLines($sql);
				}catch(Exception $e){
					__error(__FILE__,__LINE__,"Error while load xml data into [".$entity->attributes()->name."] from file '".$xmlfile."' -".$e.getMessage());
					$status=false;
				}
			}
		}else{
			__info(__FILE__,__LINE__,"XmlDataLoader::import() - entity [".$entity->attributes()->name."] not loadded: file [$xmlfile] does not exist.");
		}
		return $status;
	}
	/**
	 * Generate the insert SQL order to load data <code>$insert</code> into <code>$entity</code>.
	 * @param XMLElement $insert data from xml file from tag <code><insert/><code>.
	 * @return string sql of insert order.
	 */
	public function generateSQL($insert){
		$sql="INSERT INTO ".$insert->attributes()->table." (";
		$names=array();
		$values=array();

		//__debug(__FILE__,__LINE__,"XmlDataLoader::import() - insert=[".print_r($insert,true)."]");
		foreach($insert->field as $field){
			$names[]  = "".$field->attributes()->name;
			//$field = $this->xml->xpath("entity[@name='".$relation->attributes()->entity."']/field[@name='".("".$relation->attributes()->relationKey)."']");

			$thefield = ($this->model->getXml()->xpath("entity[@name='".$insert->attributes()->entity."']/field[@name='".("".$field->attributes()->name)."']"));
			//__debug(__FILE__,__LINE__,"XmlDataLoader::import() - thefield=[".print_r($thefield[0],true)."]");
		
			__debug(__FILE__,__LINE__,"XmlDataLoader::import() - attributes=[".print_r($thefield[0]['attribute'],true)."]");
			$values[]=$this->encapsulateData("".$field->attributes()->value,
											 "".$thefield[0]['attribute']->type[0]);
			__debug(__FILE__,__LINE__,"XmlDataLoader::import() - field=[".$field->attributes()->name."] value=[".$field->attributes()->value."]");
		}
		$sql.=implode(",",$names);
		$sql .=") values (";
		$sql.=implode(",",$values);
		$sql.=")";
		return $sql;
	}

	private function encapsulateData($value, $type){
		$ret="";
		__debug(__FILE__,__LINE__,"XmlDataLoader::encapsulateData() - start - value=[$value],type=[".print_r($type,true)."]");
		$type=$this->model->getConnection()->decodeType($type);
		if($type =="string" || $type =="date" || $type =="text"){
		   	$ret = "'".$value."'";
			__debug(__FILE__,__LINE__,"XmlDataLoader::encapsulateData() - add \"'\"");
		}else{
	   		$ret = $value;
	   	}
		__debug(__FILE__,__LINE__,"XmlDataLoader::encapsulateData() - return=[$ret]");
		return $ret;
	}
	public function setModel($model){
		$this->model = $model;
	}
	/**
	 * return the static instance of the Model Manager.
	 * create the instance if does not already exist.
	 * @param $model instance of the entity model manager.
	 */
	function getInstance($model){
		__debug(__FILE__,__LINE__,"Model::getInstance() - return instance");

		if(!isset(self::$_instance)){
			self::$_instance = new XmlDataLoader($model);
		}
		return self::$_instance;
	}
}
?>
